package com.foreknow.elm.service.impl;

import com.foreknow.elm.dao.BusinessDao;
import com.foreknow.elm.dao.CartDao;
import com.foreknow.elm.dao.impl.BusinessDaoImpl;
import com.foreknow.elm.dao.impl.CartDaoImpl;
import com.foreknow.elm.po.Business;
import com.foreknow.elm.po.Cart;
import com.foreknow.elm.service.BusinessService;
import com.foreknow.elm.service.CartService;
import com.foreknow.elm.service.FoodService;
import com.foreknow.elm.util.DBUtil;

import java.util.ArrayList;
import java.util.List;

public class CartServiceImpl implements CartService {
    @Override
    public List<Cart> listCart(Object... item) {
        List<Cart> list = new ArrayList<>();
        CartDao cartDao = new CartDaoImpl();
        BusinessService businessService = new BusinessServiceImpl();
        FoodService foodService = new FoodServiceImpl();
        try {
            DBUtil.getConnection();
            list = cartDao.listCart(item);
//            for (Cart cart : list) {
//                cart.setBusiness(businessService.getBusinessById(cart.getBusinessId()));
//                cart.setFoods(foodService.listFoodByBusinessId(cart.getBusinessId()));
//            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DBUtil.close();
        }
        return list;
    }

    @Override
    public int saveCart(Cart cart) {
        int result = 0;
        CartDao dao = new CartDaoImpl();
        try {
            DBUtil.getConnection();
            DBUtil.beginTransaction();
            result = dao.saveCart(cart);
            DBUtil.commitTransaction();
        } catch (Exception e) {
            e.printStackTrace();
            try {
                DBUtil.rollbackTransaction();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

    @Override
    public int updateCart(Cart cart) {
        int result = 0;
        CartDao dao = new CartDaoImpl();
        try {
            DBUtil.getConnection();
            DBUtil.beginTransaction();
            result = dao.updateCart(cart);
            DBUtil.commitTransaction();
        } catch (Exception e) {
            e.printStackTrace();
            try {
                DBUtil.rollbackTransaction();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

    @Override
    public int removeCart(Object... items) {
        int result = 0;
        CartDao dao = new CartDaoImpl();
        try {
            DBUtil.getConnection();
            DBUtil.beginTransaction();
            result = dao.removeCart(items);
            DBUtil.commitTransaction();
        } catch (Exception e) {
            e.printStackTrace();
            try {
                DBUtil.rollbackTransaction();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }
}
